package com.heima.comment.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    private GreenTextScan textScan;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
//        1. 校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//        评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if (StringUtils.isBlank(dto.getCommentId())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论id不能为空");
        }
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
//        2. 条件查询评论回复信息 条件:  commentId = 评论id and createdTime 小于 minDate
//        创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()));
        query.limit(dto.getSize());
        query.with(Sort.by(
                Sort.Order.desc("createdTime")
        ));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);

//        3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //	3.1 如果未登录直接 返回评论回复列表
            return ResponseResult.okResult(apCommentRepays);
        }
        //	3.2 如果登录，需要判断哪些回复点过赞
        //	基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        List<String> list = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentRepayId").in(list).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> repayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);

//	     遍历 当前回复列表，将每一个回复信息 封装成 vo
        List<ApCommentRepayVO> voList = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay, apCommentRepayVO);
            if (repayLikes.size() == 0) {
                return ResponseResult.okResult(apCommentRepays);
            }
            //判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
            for (ApCommentRepayLike repayLike : repayLikes) {
                if (repayLike.getCommentRepayId().equals(apCommentRepay.getId())){
                    apCommentRepayVO.setOperation((short) 0);
                }
                voList.add(apCommentRepayVO);
            }
        }

        return ResponseResult.okResult(voList);
    }

    /**
     * 保存回复
     *
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {

//        1. 参数校验:
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//        是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "内容不能为空");
        }
        if (StringUtils.isNotBlank(dto.getContent()) && dto.getContent().length() > 140) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "内容不能大于140个字符");
        }
//        回复内容安全校验

//       简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
        String content = handleTextScan(dto.getContent());
//        2. 根据评论id查询评论信息  检查是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        3. 保存评论回复信息
        ApCommentRepay commentRepay = new ApCommentRepay();
        commentRepay.setAuthorId(user.getId());
        commentRepay.setAuthorName(user.getName());
        commentRepay.setCommentId(dto.getCommentId());
        commentRepay.setContent(content);
        commentRepay.setLikes(0);
        commentRepay.setCreatedTime(new Date());
        commentRepay.setUpdatedTime(new Date());
        ApCommentRepay apCommentRepay = mongoTemplate.save(commentRepay);
//        4. 修改评论信息中回复数量 + 1
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(apCommentRepay);
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
//        1. 校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//       回复id不能为空   operation 必须 0 或 1
        if (dto.getCommentRepayId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "回复id不能为空");
        }
        if (dto.getOperation() != 0 && dto.getOperation() != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "cao");
        }
//       校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
//       校验回复信息是否存在
        Query query = Query.query(Criteria.where("authorId").is(user.getId())
                .and("id").is(dto.getCommentRepayId()));
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(query, ApCommentRepay.class);
        if (apCommentRepay == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "回复信息不存在");
        }
//        2. 如果是点赞  判断是否点过赞
        Query query1 = Query.query(Criteria.where("authorId").is(user.getId())
                .and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(query1, ApCommentRepayLike.class);
        Map<String, Integer> map = new HashMap<>();
        if (dto.getOperation() == 0) {
            if (commentRepayLike != null) {
                //      点过赞提示请勿重复点赞
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");
            }
            //      未点过赞， 保存点赞信息
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            apCommentRepayLike.setOperation((short) 0);
            mongoTemplate.save(apCommentRepayLike);
            //       并将回复信息的点赞数量字段+1
            Integer likes = apCommentRepay.getLikes();
            apCommentRepay.setLikes(likes + 1);
            mongoTemplate.save(apCommentRepay);
            map.put("likes", apCommentRepay.getLikes());
            return ResponseResult.okResult(map);
        }
//        3. 如果是取消赞
        if (commentRepayLike == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        } else {
            //      删除点赞信息
            mongoTemplate.remove(commentRepayLike);
            //     并将回复信息的点赞数量字段-1
            Integer likes = apCommentRepay.getLikes();
            if (likes >= 1) {
                apCommentRepay.setLikes(likes - 1);
                mongoTemplate.save(apCommentRepay);
                map.put("likes", apCommentRepay.getLikes());
                return ResponseResult.okResult(map);
            } else {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
            }
        }
//
//        4. 返回当前回复的最新点赞数量      数据的key:  likes
        return null;
    }

    /**
     * 阿里云的文本审核
     *
     * @param content
     * @return
     */
    private String handleTextScan(String content) {
        try {
            Map map = textScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            if (!suggestion.equals("pass")) {
                String content1 = map.get("filteredContent").toString();
                return content1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }
}
